# coding:utf-8
import codecs
import csv
import datetime
import json
import os
import time
import urllib2
import zipfile

from django.db import connection 
from django.db.models.query_utils import Q
from django.http.response import HttpResponse, StreamingHttpResponse, \
    HttpResponseRedirect
from django.shortcuts import render_to_response

from user.models import AccgmUser, AccgmUserMessage, AccgmBackgroundUser
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

def userLoginIndex(request):
    print request.session['user']
    return render_to_response('userLoginIndex.html')

def login(request):
    result = {}
    username = request.GET.get('username')
    password = request.GET.get('password')
    accgmBackgroundUser = AccgmBackgroundUser.objects.filter(username=username)
    if len(list(accgmBackgroundUser)) > 0:
        if accgmBackgroundUser[0].password == password:
                result['msg'] = '登录成功'
                result['result'] = 1
                request.session['user'] = username
                return HttpResponse(json.dumps(result), content_type="application/json")
        else:
            result['msg'] = '密码错误'
            result['result'] = -1
            return HttpResponse(json.dumps(result), content_type="application/json")           
    else:
        result['msg'] = '账号错误'
        result['result'] = -1
        return HttpResponse(json.dumps(result), content_type="application/json")

def userIndex(request):
    if request.session.get('user') is None or request.session.get('user') == '':
        return render_to_response('userLoginIndex.html') 
    pageNumber = request.GET.get('pageNumber')
    isOrderByCheckMessage = request.GET.get('isOrderByCheckMessage')
    isOrderByAccount = request.GET.get('isOrderByAccount')
    isOrderBySex = request.GET.get('isOrderBySex')
    isOrderByBirthday = request.GET.get('isOrderByBirthday')
    searchContent = request.GET.get('searchContent')
    pageSize = 25
    accgmUserList = []
    previousPageUrl = '/showUser/?pageNumber='+str(int(pageNumber)-1)
    nextPageUrl = '/showUser/?pageNumber='+str(int(pageNumber)+1)
    if (isOrderByCheckMessage is None and isOrderByAccount is None and isOrderBySex is None and isOrderByBirthday is None and searchContent is None) or searchContent == '':
        accgmUserList = AccgmUser.objects.order_by('-addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByCheckMessage is not None:
        previousPageUrl = previousPageUrl+'&isOrderByCheckMessage='+str(isOrderByCheckMessage)
        nextPageUrl = nextPageUrl+'&isOrderByCheckMessage='+str(isOrderByCheckMessage)
        if isOrderByCheckMessage == '0':
            accgmUserList = AccgmUser.objects.order_by('-checkmessage')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByCheckMessage == '1':
            accgmUserList = AccgmUser.objects.order_by('checkmessage')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByAccount is not None:
        previousPageUrl = previousPageUrl+'&isOrderByAccount='+str(isOrderByAccount)
        nextPageUrl = nextPageUrl+'&isOrderByAccount='+str(isOrderByAccount)
        if isOrderByAccount == '0':
            accgmUserList = AccgmUser.objects.order_by('-id')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByAccount == '1':
            accgmUserList = AccgmUser.objects.order_by('id')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderBySex is not None:
        previousPageUrl = previousPageUrl+'&isOrderBySex='+str(isOrderBySex)
        nextPageUrl = nextPageUrl+'&isOrderBySex='+str(isOrderBySex)
        if isOrderBySex == '0':
            accgmUserList = AccgmUser.objects.order_by('-sex')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderBySex == '1':
            accgmUserList = AccgmUser.objects.order_by('sex')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByBirthday is not None:
        previousPageUrl = previousPageUrl+'&isOrderByBirthday='+str(isOrderByBirthday)
        nextPageUrl = nextPageUrl+'&isOrderByBirthday='+str(isOrderByBirthday)
        if isOrderByBirthday == '0':
            accgmUserList = AccgmUser.objects.order_by('-birthday')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByBirthday == '1':
            accgmUserList = AccgmUser.objects.order_by('birthday')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if searchContent is not None and searchContent != '':
        previousPageUrl = previousPageUrl+'&searchContent='+str(searchContent)
        nextPageUrl = nextPageUrl+'&searchContent='+str(searchContent)
        accgmUserList = AccgmUser.objects.filter(Q(name__contains=searchContent) | Q(username__contains=searchContent))[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    accgmUserList2 = []
    for accgmUser in accgmUserList:
        if accgmUser.birthday != '':
            brithday = datetime.datetime.strptime(accgmUser.birthday.replace(u'年','-').replace(u'月','-').replace(u'日',''), "%Y-%m-%d")
            accgmUser.birthday = datetime.datetime.now().year -  brithday.year 
        accgmUserList2.append(accgmUser)
    size = len(list(accgmUserList))
    if pageNumber == '0':
        previousPageUrl = ''
    if size < 25:
        nextPageUrl = ''
    if searchContent is None:
        searchContent = ''
    return render_to_response('userIndex.html',{'accgmUserList':accgmUserList2,'size':size,'previousPageUrl':previousPageUrl,'nextPageUrl':nextPageUrl,'searchContent':searchContent})

def userMessage(request):
    if request.session.get('user') is None or request.session.get('user') == '':
        return render_to_response('userLoginIndex.html') 
    userId = request.GET.get('userId')
    pageNumber = request.GET.get('pageNumber')
    isOrderByAddTime = request.GET.get('isOrderByAddTime')
    isOrderByDeviceId = request.GET.get('isOrderByDeviceId')
    isOrderByCollect = request.GET.get('isOrderByCollect')
    pageSize = 25
    previousPageUrl = '/showUserMessage/?userId='+str(userId)+'&pageNumber='+str(int(pageNumber)-1)
    nextPageUrl = '/showUserMessage/?userId='+str(userId)+'&pageNumber='+str(int(pageNumber)+1)
    accgmUserMessageList = []
    if isOrderByAddTime is None and isOrderByDeviceId is None and isOrderByCollect is None:
        if userId == '0':
            accgmUserMessageList = AccgmUserMessage.objects.order_by('-addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        else:
            accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('-addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByAddTime is not None:
        previousPageUrl = previousPageUrl+'&isOrderByCollect='+str(isOrderByAddTime)
        nextPageUrl = nextPageUrl+'&isOrderByCollect='+str(isOrderByAddTime)
        if isOrderByAddTime == '0':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('-addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('-addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByAddTime == '1':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('addtime')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByDeviceId is not None:
        previousPageUrl = previousPageUrl+'&isOrderByDeviceId='+str(isOrderByDeviceId)
        nextPageUrl = nextPageUrl+'&isOrderByDeviceId='+str(isOrderByDeviceId)
        if isOrderByDeviceId == '0':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('-deviceid')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('-deviceid')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByDeviceId == '1':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('deviceid')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('deviceid')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    if isOrderByCollect is not None:
        previousPageUrl = previousPageUrl+'&isOrderByCollect='+str(isOrderByCollect)
        nextPageUrl = nextPageUrl+'&isOrderByCollect='+str(isOrderByCollect)
        if isOrderByCollect == '0':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('-collectloc','collect')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('-collectloc','collect')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
        elif isOrderByCollect == '1':
            if userId == '0':
                accgmUserMessageList = AccgmUserMessage.objects.order_by('collectloc','collect')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(userid=userId).order_by('collectloc','collect')[int(pageNumber)*pageSize:(int(pageNumber)+1)*pageSize]
    accgmUserMessageList2 = []
    for accgmUserMessage in accgmUserMessageList:
        accgmUser = AccgmUser.objects.filter(id=accgmUserMessage.userid)
        if len(list(accgmUser)) > 0:
            accgmUserMessage.account = accgmUser[0].username
        else:
            accgmUserMessage.account = ''
        accgmUserMessageList2.append(accgmUserMessage)
    size = len(list(accgmUserMessageList));
    if pageNumber == '0':
        previousPageUrl = ''
    if size < 25:
        nextPageUrl = ''
    return render_to_response('userMessageIndex.html',{'accgmUserMessageList':accgmUserMessageList2,'size':size,'previousPageUrl':previousPageUrl,'nextPageUrl':nextPageUrl,'userId':userId})

def cntIndex(request):
    if request.session.get('user') is None or request.session.get('user') == '':
        return render_to_response('userLoginIndex.html') 
    result = {}
    userCnt = AccgmUser.objects.all().count()
    manUserCnt = AccgmUser.objects.filter(sex='M').count()
    womanUserCnt = AccgmUser.objects.filter(sex='F').count()
    checkMessage0Cnt = AccgmUser.objects.filter(checkmessage=0).count()
    checkMessage1Cnt = AccgmUser.objects.filter(checkmessage=1).count()
    checkMessage2Cnt = AccgmUser.objects.filter(checkmessage=2).count()
    
    age0_10CheckMessage0Cnt = 0
    age0_10CheckMessage1Cnt = 0
    age0_10CheckMessage2Cnt = 0
    searchAge0_10Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 0 and accgm_user_age.age <= 10 group by accgm_user_age.checkMessage'
    searchAge0_10cursor = connection.cursor()  
    searchAge0_10cursor.execute(searchAge0_10Sql)
    for age0_10CheckMessageCnt in searchAge0_10cursor.fetchall():
        if age0_10CheckMessageCnt[1] == 0:
            age0_10CheckMessage0Cnt = age0_10CheckMessageCnt[2]
        elif age0_10CheckMessageCnt[1] == 1:
            age0_10CheckMessage1Cnt = age0_10CheckMessageCnt[2]
        elif age0_10CheckMessageCnt[1] == 2:
            age0_10CheckMessage2Cnt = age0_10CheckMessageCnt[2]
            
    age11_20CheckMessage0Cnt = 0
    age11_20CheckMessage1Cnt = 0
    age11_20CheckMessage2Cnt = 0
    searchAge11_20Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 11 and accgm_user_age.age <= 20 group by accgm_user_age.checkMessage'
    searchAge11_20cursor = connection.cursor()  
    searchAge11_20cursor.execute(searchAge11_20Sql)
    for age11_20CheckMessageCnt in searchAge11_20cursor.fetchall():
        if age11_20CheckMessageCnt[1] == 0:
            age11_20CheckMessage0Cnt = age11_20CheckMessageCnt[2]
        elif age11_20CheckMessageCnt[1] == 1:
            age11_20CheckMessage1Cnt = age11_20CheckMessageCnt[2]
        elif age11_20CheckMessageCnt[1] == 2:
            age11_20CheckMessage2Cnt = age11_20CheckMessageCnt[2]
            
    age21_30CheckMessage0Cnt = 0
    age21_30CheckMessage1Cnt = 0
    age21_30CheckMessage2Cnt = 0
    searchAge21_30Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 21 and accgm_user_age.age <= 30 group by accgm_user_age.checkMessage'
    searchAge21_30cursor = connection.cursor()  
    searchAge21_30cursor.execute(searchAge21_30Sql)
    for age21_30CheckMessageCnt in searchAge21_30cursor.fetchall():
        if age21_30CheckMessageCnt[1] == 0:
            age21_30CheckMessage0Cnt = age21_30CheckMessageCnt[2]
        elif age21_30CheckMessageCnt[1] == 1:
            age21_30CheckMessage1Cnt = age21_30CheckMessageCnt[2]
        elif age21_30CheckMessageCnt[1] == 2:
            age21_30CheckMessage2Cnt = age21_30CheckMessageCnt[2]
            
    age31_40CheckMessage0Cnt = 0
    age31_40CheckMessage1Cnt = 0
    age31_40CheckMessage2Cnt = 0
    searchAge31_40Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 31 and accgm_user_age.age <= 40 group by accgm_user_age.checkMessage'
    searchAge31_40cursor = connection.cursor()  
    searchAge31_40cursor.execute(searchAge31_40Sql)
    for age31_40CheckMessageCnt in searchAge31_40cursor.fetchall():
        if age31_40CheckMessageCnt[1] == 0:
            age31_40CheckMessage0Cnt = age31_40CheckMessageCnt[2]
        elif age31_40CheckMessageCnt[1] == 1:
            age31_40CheckMessage1Cnt = age31_40CheckMessageCnt[2]
        elif age31_40CheckMessageCnt[1] == 2:
            age31_40CheckMessage2Cnt = age31_40CheckMessageCnt[2]
            
    age41_50CheckMessage0Cnt = 0
    age41_50CheckMessage1Cnt = 0
    age41_50CheckMessage2Cnt = 0
    searchAge41_50Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 41 and accgm_user_age.age <= 50 group by accgm_user_age.checkMessage'
    searchAge41_50cursor = connection.cursor()  
    searchAge41_50cursor.execute(searchAge41_50Sql)
    for age41_50CheckMessageCnt in searchAge41_50cursor.fetchall():
        if age41_50CheckMessageCnt[1] == 0:
            age41_50CheckMessage0Cnt = age41_50CheckMessageCnt[2]
        elif age41_50CheckMessageCnt[1] == 1:
            age41_50CheckMessage1Cnt = age41_50CheckMessageCnt[2]
        elif age41_50CheckMessageCnt[1] == 2:
            age41_50CheckMessage2Cnt = age41_50CheckMessageCnt[2]
    
    age51_60CheckMessage0Cnt = 0
    age51_60CheckMessage1Cnt = 0
    age51_60CheckMessage2Cnt = 0
    searchAge51_60Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 51 and accgm_user_age.age <= 60 group by accgm_user_age.checkMessage'
    searchAge51_60cursor = connection.cursor()  
    searchAge51_60cursor.execute(searchAge51_60Sql)
    for age51_60CheckMessageCnt in searchAge51_60cursor.fetchall():
        if age51_60CheckMessageCnt[1] == 0:
            age51_60CheckMessage0Cnt = age51_60CheckMessageCnt[2]
        elif age21_30CheckMessageCnt[1] == 1:
            age51_60CheckMessage1Cnt = age51_60CheckMessageCnt[2]
        elif age21_30CheckMessageCnt[1] == 2:
            age51_60CheckMessage2Cnt = age51_60CheckMessageCnt[2]
            
    age61_70CheckMessage0Cnt = 0
    age61_70CheckMessage1Cnt = 0
    age61_70CheckMessage2Cnt = 0
    searchAge61_70Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 61 and accgm_user_age.age <= 70 group by accgm_user_age.checkMessage'
    searchAge61_70cursor = connection.cursor()  
    searchAge61_70cursor.execute(searchAge61_70Sql)
    for age61_70CheckMessageCnt in searchAge61_70cursor.fetchall():
        if age61_70CheckMessageCnt[1] == 0:
            age61_70CheckMessage0Cnt = age61_70CheckMessageCnt[2]
        elif age61_70CheckMessageCnt[1] == 1:
            age61_70CheckMessage1Cnt = age61_70CheckMessageCnt[2]
        elif age61_70CheckMessageCnt[1] == 2:
            age61_70CheckMessage2Cnt = age61_70CheckMessageCnt[2]
            
    age71_80CheckMessage0Cnt = 0
    age71_80CheckMessage1Cnt = 0
    age71_80CheckMessage2Cnt = 0
    searchAge71_80Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age >= 71 and accgm_user_age.age <= 80 group by accgm_user_age.checkMessage'
    searchAge71_80cursor = connection.cursor()  
    searchAge71_80cursor.execute(searchAge71_80Sql)
    for age71_80CheckMessageCnt in searchAge71_80cursor.fetchall():
        if age71_80CheckMessageCnt[1] == 0:
            age71_80CheckMessage0Cnt = age71_80CheckMessageCnt[2]
        elif age71_80CheckMessageCnt[1] == 1:
            age71_80CheckMessage1Cnt = age71_80CheckMessageCnt[2]
        elif age71_80CheckMessageCnt[1] == 2:
            age71_80CheckMessage2Cnt = age71_80CheckMessageCnt[2]
            
    ageAfter80CheckMessage0Cnt = 0
    ageAfter80CheckMessage1Cnt = 0
    ageAfter80CheckMessage2Cnt = 0
    searchAgeAfter80Sql = 'select age,checkMessage,count(id) as cnt from (select id,(year(now())-year(birthday)-1) + ( DATE_FORMAT(birthday, "%m%d") <= DATE_FORMAT(NOW(), "%m%d") ) as age,checkMessage  from  accgm_user) as accgm_user_age where accgm_user_age.age > 80 group by accgm_user_age.checkMessage'
    searchAgeAfter80cursor = connection.cursor()  
    searchAgeAfter80cursor.execute(searchAgeAfter80Sql)
    for ageAfter80CheckMessageCnt in searchAgeAfter80cursor.fetchall():
        if ageAfter80CheckMessageCnt[1] == 0:
            ageAfter80CheckMessage0Cnt = ageAfter80CheckMessageCnt[2]
        elif ageAfter80CheckMessageCnt[1] == 1:
            ageAfter80CheckMessage1Cnt = ageAfter80CheckMessageCnt[2]
        elif ageAfter80CheckMessageCnt[1] == 2:
            ageAfter80CheckMessage2Cnt = ageAfter80CheckMessageCnt[2]
            
    earPiercingUserCnt = AccgmUser.objects.filter(isearpiercing='Y').count()
    
    maxBloodSugar = 0.0
    searchMaxBloodSugarSql = 'select max(bloodSugar1),max(bloodSugar2),max(bloodSugar3) from accgm_user_message'
    searchMaxBloodSugarcursor = connection.cursor()  
    searchMaxBloodSugarcursor.execute(searchMaxBloodSugarSql)
    for searchMaxBloodSugar in searchMaxBloodSugarcursor.fetchall():
        maxBloodSugar = float(searchMaxBloodSugar[0])
        if float(searchMaxBloodSugar[1]) > maxBloodSugar:
            maxBloodSugar = float(searchMaxBloodSugar[1])
        if float(searchMaxBloodSugar[2]) > maxBloodSugar:
            maxBloodSugar = float(searchMaxBloodSugar[2])
            
    minBloodSugar = 0.0
    searchMinBloodSugarSql = 'select min(bloodSugar1),min(bloodSugar2),min(bloodSugar3) from accgm_user_message'
    searchMinBloodSugarcursor = connection.cursor()  
    searchMinBloodSugarcursor.execute(searchMinBloodSugarSql)
    for searchMinBloodSugar in searchMinBloodSugarcursor.fetchall():
        minBloodSugar = float(searchMinBloodSugar[0])
        if float(searchMinBloodSugar[1]) < minBloodSugar:
            minBloodSugar = float(searchMinBloodSugar[1])
        if float(searchMinBloodSugar[2]) < minBloodSugar:
            minBloodSugar = float(searchMinBloodSugar[2])
            
    earLobeWidthCntList = []
    searchEarLobeWidthSql = 'select earlobeWidth,count(id) from accgm_user group by earlobeWidth'
    searchEarLobeWidthcursor = connection.cursor()  
    searchEarLobeWidthcursor.execute(searchEarLobeWidthSql)
    for searchEarLobeWidth in searchEarLobeWidthcursor.fetchall():
        earLobeWidthCnt = str(searchEarLobeWidth[0])+'mm：'+str(searchEarLobeWidth[1])+'人'
        earLobeWidthCntList.append(earLobeWidthCnt)
            
    result = {'userCnt':userCnt,
             'manUserCnt':manUserCnt,
             'womanUserCnt':womanUserCnt,
             'checkMessage0Cnt':checkMessage0Cnt,
             'checkMessage1Cnt':checkMessage1Cnt,
             'checkMessage2Cnt':checkMessage2Cnt,
             'age0_10CheckMessageCnt':age0_10CheckMessage0Cnt+age0_10CheckMessage1Cnt+age0_10CheckMessage2Cnt,
             'age0_10CheckMessage0Cnt':age0_10CheckMessage0Cnt,
             'age0_10CheckMessage1Cnt':age0_10CheckMessage1Cnt,
             'age0_10CheckMessage2Cnt':age0_10CheckMessage2Cnt,
             'age11_20CheckMessageCnt':age11_20CheckMessage0Cnt+age11_20CheckMessage1Cnt+age11_20CheckMessage2Cnt,
             'age11_20CheckMessage0Cnt':age11_20CheckMessage0Cnt,
             'age11_20CheckMessage1Cnt':age11_20CheckMessage1Cnt,
             'age11_20CheckMessage2Cnt':age11_20CheckMessage2Cnt,
             'age21_30CheckMessageCnt':age21_30CheckMessage0Cnt+age21_30CheckMessage1Cnt+age21_30CheckMessage2Cnt,
             'age21_30CheckMessage0Cnt':age21_30CheckMessage0Cnt,
             'age21_30CheckMessage1Cnt':age21_30CheckMessage1Cnt,
             'age21_30CheckMessage2Cnt':age21_30CheckMessage2Cnt,
             'age31_40CheckMessageCnt':age31_40CheckMessage0Cnt+age31_40CheckMessage1Cnt+age31_40CheckMessage2Cnt,
             'age31_40CheckMessage0Cnt':age31_40CheckMessage0Cnt,
             'age31_40CheckMessage1Cnt':age31_40CheckMessage1Cnt,
             'age31_40CheckMessage2Cnt':age31_40CheckMessage2Cnt,
             'age51_60CheckMessageCnt':age51_60CheckMessage0Cnt+age51_60CheckMessage1Cnt+age51_60CheckMessage2Cnt,
             'age51_60CheckMessage0Cnt':age51_60CheckMessage0Cnt,
             'age51_60CheckMessage1Cnt':age51_60CheckMessage1Cnt,
             'age51_60CheckMessage2Cnt':age51_60CheckMessage2Cnt,
             'age61_70CheckMessageCnt':age61_70CheckMessage0Cnt+age61_70CheckMessage1Cnt+age61_70CheckMessage2Cnt,
             'age61_70CheckMessage0Cnt':age61_70CheckMessage0Cnt,
             'age61_70CheckMessage1Cnt':age61_70CheckMessage1Cnt,
             'age61_70CheckMessage2Cnt':age61_70CheckMessage2Cnt,
             'age71_80CheckMessageCnt':age71_80CheckMessage0Cnt+age71_80CheckMessage1Cnt+age71_80CheckMessage2Cnt,
             'age71_80CheckMessage0Cnt':age71_80CheckMessage0Cnt,
             'age71_80CheckMessage1Cnt':age71_80CheckMessage1Cnt,
             'age71_80CheckMessage2Cnt':age71_80CheckMessage2Cnt,
             'ageAfter80CheckMessageCnt':ageAfter80CheckMessage0Cnt+ageAfter80CheckMessage1Cnt+ageAfter80CheckMessage2Cnt,
             'ageAfter80CheckMessage0Cnt':ageAfter80CheckMessage0Cnt,
             'ageAfter80CheckMessage1Cnt':ageAfter80CheckMessage1Cnt,
             'ageAfter80CheckMessage2Cnt':ageAfter80CheckMessage2Cnt,
             'earPiercingUserCnt':earPiercingUserCnt,
             'maxBloodSugar':maxBloodSugar,
             'minBloodSugar':minBloodSugar,
             'earLobeWidthCntList':earLobeWidthCntList}
            
    return render_to_response('userCntIndex.html',result)

def downloadCSV(request):
    if request.session.get('user') is None or request.session.get('user') == '':
        return render_to_response('userLoginIndex.html') 
    accgmUserMessageId = request.GET.get('accgmUserMessageId')
    getCSVByTime = request.GET.get('getCSVByTime')
    userId = request.GET.get('userId')
    starUserAccount = request.GET.get('starUserAccount')
    endUserAccount = request.GET.get('endUserAccount')
    
    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break    
        
    if getCSVByTime is None or getCSVByTime == '': 
        account = ''
        addTime = ''
        addTime2 = ''
        deviceId = ''
        collect = ''
        accgmUserMessageList = AccgmUserMessage.objects.filter(id=accgmUserMessageId)
        if len(list(accgmUserMessageList)) > 0:
            accgmUser = AccgmUser.objects.get(id=accgmUserMessageList[0].userid)
            account = accgmUser.username
            addTime = accgmUserMessageList[0].addtime.strftime('%Y%m%d')
            addTime = str(addTime)[2:len(addTime)]
            addTime2 = accgmUserMessageList[0].addtime.strftime('%H%M%S')
            deviceId = accgmUserMessageList[0].deviceid
            collect = str(accgmUserMessageList[0].collectloc)+str(accgmUserMessageList[0].collect)
            csvfile = file('/data/accgm_api/download/'+account+'_'+addTime+'_'+addTime2+'_'+deviceId+'_'+collect+'.csv', 'wb')
            csvfile.write(codecs.BOM_UTF8)
            writer = csv.writer(csvfile, dialect='excel')
            csvData = []
            csvData.append(['采集的日期及时间'])
            csvData.append([accgmUserMessageList[0].addtime.strftime('%Y-%m-%d %H:%M')])
            csvData.append(['版本号'])
            csvData.append([accgmUserMessageList[0].venderid])
            csvData.append(['采集设备ID'])
            csvData.append([accgmUserMessageList[0].deviceid])
            csvData.append(['帐号'])
            csvData.append([accgmUser.username])
            csvData.append(['姓名'])
            csvData.append([accgmUser.name])
            csvData.append(['姓別'])
            csvData.append([accgmUser.sex])
            csvData.append(['出生日期'])
            csvData.append([accgmUser.birthday])
            csvData.append(['高度'])
            csvData.append([accgmUser.height])
            csvData.append(['体重'])
            csvData.append([accgmUser.weight])
            csvData.append(['糖尿病類型'])
            csvData.append([accgmUser.checkmessage])
            csvData.append(['耳垂厚度'])
            csvData.append([accgmUser.earlobewidth])
            csvData.append(['有否穿耳環'])
            csvData.append([accgmUser.isearpiercing])
            csvData.append(['测量位置资料1'])
            csvData.append([accgmUserMessageList[0].collectloc])
            csvData.append(['测量位置资料2'])
            csvData.append([accgmUserMessageList[0].collect])
            csvData.append(['饮食时间选择 '])
            csvData.append([accgmUserMessageList[0].statetime])
            csvData.append(['饮食状态选择 '])
            csvData.append([accgmUserMessageList[0].state])
            csvData.append(['当前体温'])
            csvData.append([accgmUserMessageList[0].bodytemperature])
            csvData.append(['有创血糖仪1读数'])
            csvData.append([accgmUserMessageList[0].bloodsugar1])
            csvData.append(['有创血糖仪2读数'])
            csvData.append([accgmUserMessageList[0].bloodsugar2])
            csvData.append(['有创血糖仪3读数'])
            csvData.append([accgmUserMessageList[0].bloodsugar3])
            csvData.append(['今天有否吃降血糖藥'])
            csvData.append([accgmUserMessageList[0].istakedownsugar])
            csvData.append(['今天有否注射胰岛素'])
            csvData.append([accgmUserMessageList[0].isinjectinsulin])
            csvData.append(['今天有否吃退燒/止痛藥'])
            csvData.append([accgmUserMessageList[0].istakepainkiller])
            csvData.append(['测试前有无做运动'])
            csvData.append([accgmUserMessageList[0].sports])
            csvData.append(['PacketData'])
            file_url = '/data/accgm_api/download/'+accgmUserMessageList[0].dataurl.replace('http://112.74.185.9/','')
#             file_url = 'D:/bc6adeb6b9f34c11d0a0945c0c5c3e0f.m'
            file_object = open(file_url, 'r')
            while 1:
                line = file_object.readline()
                line = "".join(line.split())
                if not line:
                    break
                csvData.append([line])
                pass # do something
            writer.writerows(csvData)
            csvfile.close()
#         response = StreamingHttpResponse(file_iterator('/data/accgm_background/csv_test.csv'))
        else:
            return HttpResponse('没有可下载的数据')
        response = StreamingHttpResponse(file_iterator('/data/accgm_api/download/'+account+'_'+addTime+'_'+addTime2+'_'+deviceId+'_'+collect+'.csv'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(account+'_'+addTime+'_'+addTime2+'_'+deviceId+'_'+collect+'.csv')
    else:
        starUserId = 0
        endUserId = 0
        if starUserAccount is not None and starUserAccount != '':
            starUserId = int(starUserAccount.replace('A',''))+100000000
            endUserId = int(endUserAccount.replace('A',''))+100000000
        getCSVByTimeStr = getCSVByTime
        t = time.strptime(getCSVByTime, "%Y-%m-%d")
        y,m,d = t[0:3]
        getCSVByTime = datetime.datetime(y,m,d)
        tomorrow = getCSVByTime + datetime.timedelta(days=1)
        # 定义要创建的目录
        packpath='/data/accgm_api/download/'+str(time.time())
        packpathTimeStr = packpath
        # 调用函数
        mkdir(packpath)
        packpath=packpath+'/'+str(getCSVByTimeStr)
        mkdir(packpath)
        if userId == '0':
            if starUserId != 0:
                accgmUserMessageList = AccgmUserMessage.objects.filter(addtime__gte=getCSVByTime).filter(addtime__lt=tomorrow).filter(userid__gte=starUserId).filter(userid__lte=endUserId)
            else:
                accgmUserMessageList = AccgmUserMessage.objects.filter(addtime__gte=getCSVByTime).filter(addtime__lt=tomorrow)
        else:
            accgmUserMessageList = AccgmUserMessage.objects.filter(addtime__gte=getCSVByTime).filter(addtime__lt=tomorrow).filter(userid=userId)
        if len(list(accgmUserMessageList)) <= 0:
            return HttpResponse('没有可下载的数据')
        for accgmUserMessage in accgmUserMessageList:
            accgmUser = AccgmUser.objects.get(id=accgmUserMessage.userid)
            account = accgmUser.username
            addTime = accgmUserMessage.addtime.strftime('%Y%m%d')
            addTime = str(addTime)[2:len(addTime)]
            addTime2 = accgmUserMessage.addtime.strftime('%H%M%S')
            deviceId = accgmUserMessage.deviceid
            collect = str(accgmUserMessage.collectloc)+str(accgmUserMessageList[0].collect)
            # 调用函数
            mkdir(packpath+'/'+str(account))
            csvfile = file(packpath+'/'+str(account)+'/'+account+'_'+addTime+'_'+addTime2+'_'+deviceId+'_'+collect+'.csv', 'wb')
            csvfile.write(codecs.BOM_UTF8)
            writer = csv.writer(csvfile, dialect='excel')
            csvData = []
            csvData.append(['采集的日期及时间'])
            csvData.append([accgmUserMessage.addtime.strftime('%Y-%m-%d %H:%M')])
            csvData.append(['版本号'])
            csvData.append([accgmUserMessage.venderid])
            csvData.append(['采集设备ID'])
            csvData.append([accgmUserMessage.deviceid])
            csvData.append(['帐号'])
            csvData.append([accgmUser.username])
            csvData.append(['姓名'])
            csvData.append([accgmUser.name])
            csvData.append(['姓別'])
            csvData.append([accgmUser.sex])
            csvData.append(['出生日期'])
            csvData.append([accgmUser.birthday])
            csvData.append(['高度'])
            csvData.append([accgmUser.height])
            csvData.append(['体重'])
            csvData.append([accgmUser.weight])
            csvData.append(['糖尿病類型'])
            csvData.append([accgmUser.checkmessage])
            csvData.append(['耳垂厚度'])
            csvData.append([accgmUser.earlobewidth])
            csvData.append(['有否穿耳環'])
            csvData.append([accgmUser.isearpiercing])
            csvData.append(['测量位置资料1'])
            csvData.append([accgmUserMessage.collectloc])
            csvData.append(['测量位置资料2'])
            csvData.append([accgmUserMessage.collect])
            csvData.append(['饮食时间选择 '])
            csvData.append([accgmUserMessage.statetime])
            csvData.append(['饮食状态选择 '])
            csvData.append([accgmUserMessage.state])
            csvData.append(['当前体温'])
            csvData.append([accgmUserMessage.bodytemperature])
            csvData.append(['有创血糖仪1读数'])
            csvData.append([accgmUserMessage.bloodsugar1])
            csvData.append(['有创血糖仪2读数'])
            csvData.append([accgmUserMessage.bloodsugar2])
            csvData.append(['有创血糖仪3读数'])
            csvData.append([accgmUserMessage.bloodsugar3])
            csvData.append(['今天有否吃降血糖藥'])
            csvData.append([accgmUserMessage.istakedownsugar])
            csvData.append(['今天有否注射胰岛素'])
            csvData.append([accgmUserMessage.isinjectinsulin])
            csvData.append(['今天有否吃退燒/止痛藥'])
            csvData.append([accgmUserMessage.istakepainkiller])
            csvData.append(['测试前有无做运动'])
            csvData.append([accgmUserMessage.sports])
            csvData.append(['PacketData'])
            file_url = '/data/accgm_api/download/'+accgmUserMessage.dataurl.replace('http://112.74.185.9/','')
            print 'url============'+file_url
            file_object = open(file_url, 'r')
            while 1:
                line = file_object.readline()
                line = "".join(line.split())
                if not line:
                    break
                csvData.append([line])
                pass # do something
            writer.writerows(csvData)
            csvfile.close()
        zpfd = zipfile.ZipFile(packpath+'.zip', mode='w',compression=zipfile.ZIP_STORED)
        startdir = packpath
        for dirpath, dirnames, filenames in os.walk(startdir):
            print len(filenames)
            for filename in filenames:
#                 zpfd.write(os.path.join(dirpath, filename),str(os.path.join(dirpath, filename)).replace(packpathTimeStr,''))
#                 print dirpath+'/'+filename
                zpfd.write(dirpath+'/'+filename,str(dirpath+'/'+filename).replace(packpathTimeStr,''), zipfile.ZIP_DEFLATED)
        zpfd.close()
#         response = StreamingHttpResponse(file_iterator('/data/accgm_background/csv_test.csv'))
#         response = StreamingHttpResponse(file_iterator(packpath+'.zip'))
#         response['Content-Type'] = 'application/zip'
#         response['Content-Disposition'] = 'attachment;filename="{0}"'.format(getCSVByTimeStr+'.zip')
#         print str(packpath+'.zip').replace('D:/')
        return HttpResponseRedirect('http://112.74.185.9/'+str(packpath+'.zip').replace('/data/accgm_api/download',''))
    return response 

def updateUserPassword(request):
    result = {}
    if request.session.get('user') is None or request.session.get('user') == '':
        return render_to_response('userLoginIndex.html') 
    userId = request.GET.get('userId')
    password = request.GET.get('password')
    url = "http://112.74.185.9:8088/accgm/updateUserPassword?isBgRequest=1&userId="+str(userId)+"&password="+str(password)
    req = urllib2.Request(url)
    res_data = urllib2.urlopen(req)
    res = res_data.read()
    responseJSON = json.loads(res)
    if responseJSON['result'] == 1:
        result['msg'] = '更新成功'
        result['result'] = 1
        return HttpResponse(json.dumps(result), content_type="application/json")
    else:
        result['msg'] = '更新失败'
        result['result'] = -1
        return HttpResponse(json.dumps(result), content_type="application/json")   
    
def mkdir(path):
    # 引入模块
    import os
 
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")
 
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
 
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        print path+' 创建成功'
        # 创建目录操作函数
        os.makedirs(path)
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print path+' 目录已存在'
        return False
